(function(factory) {
	if (typeof define === "function" && define.amd) {
		// AMD. Register as an anonymous module.
		define(factory);
	} else {
		// Browser globals
		factory();
	}
}(function() {
	/**
	 * @author 李球 <service@hteos.com>
	 * @class HteOS.Taskbar 桌面任务栏组件
	 * @singleton
	 */
	HteOS.Taskbar = {

		/**
		 * 任务数量
		 *
		 * @property
		 */
		tasks: 0,

		/**
		 * 默认任务按钮的宽度
		 *
		 * @property
		 */
		width: 160,

		/**
		 * 任务栏是否固定在底部
		 *
		 * @property
		 */
		fixed: false,

		/**
		 * 任务栏是否有溢出
		 *
		 * @property
		 */
		overflow: false,
		
		margin:4,
		
		actions : [{
			"title" : "桌面",
			"icon" : "glyphicon glyphicon-th-large",
			"position" : "left",
			"handler" : "var windows=HteOS.window.WindowManager.windows;for(var win in windows){HteOS.window.WindowManager.get(win).hide()}$(\".hte-metro-group\").css({\"transform\":\"translateX(50px) scale(0.8)\",\"opacity\":0});window.setTimeout(function(){HteOS.Metro.animate()},200);"
		},{
			"title" : "我的HteOS",
			"icon" : "glyphicon glyphicon-user",
			"position" : "left",
			"app" : "myhteos"
		},{
			"title" : "应用管理",
			"icon" : "glyphicon glyphicon-list",
			"position" : "left",
			"handler" : "HteOS.TaskManager.start({id:\"appmanager\",name:\"应用管理\",path:HteOS.basePath+\"tpl/overview.html\",mode:\"dock\"});"
		},{
			"title" : "应用市场",
			"icon" : "glyphicon glyphicon-folder-close",
			"position" : "right",
			"app" : "store"	
		},{
			"title" : "即时通讯",
			"position" : "right",
			"icon" : "glyphicon glyphicon-comment",
			"handler" : "HteOS.TaskManager.start({id:\"messager\",name:\"即时通讯\",path:HteOS.basePath+\"tpl/messager.html\",mode:\"dock\"});"
		}, {
			"title" : "个性化设置",
			"position" : "right",
			"icon" : "glyphicon glyphicon glyphicon-cog",
			"app" : "settings"
		}],

		
		/**
		 * 初始化任务栏，主要对任务栏按钮、窗口等组件做了事件监听
		 */
		init: function() {
			var me = this;
			
			$("<div class=\"hte-taskbar\">" +
					"<div class=\"hte-taskbar-action-left\"></div>"+
					"<div class=\"hte-taskbar-inner\"></div>" + 
					"<div class=\"hte-taskbar-action-right\"></div>"+
					"<div class=\"hte-taskbar-nav left\">" + 
				"        <span class=\"glyphicon glyphicon-chevron-left\"></span>" + 
				"      </div>" + 
				"      <div class=\"hte-taskbar-nav right\">" + 
				"        <span class=\"glyphicon glyphicon-chevron-right\"></span>" + 
				"      </div>" + 
				"    </div>").appendTo(HteOS.getContainer());
			
			me.inner = $(".hte-taskbar-inner");
			me.contextmenu();
			me.initActions();
			me.dragdrop();
			me.initEvents();
		},
		
		initEvents : function(){
			
			var me = this;
			
			$(window).resize(function() {
				me.layout();
			});
			
			$(".hte-taskbar-nav.right").click(function() {
				me.inner.animate({
					scrollLeft: me.inner.scrollLeft() + 100
				});
			});

			$(".hte-taskbar-nav.left").click(function() {
				me.inner.animate({
					scrollLeft: me.inner.scrollLeft() - 100
				});
			});

			
			$(document.body).on("click", ".hte-task", function() {
				var windowId = $(this).data("windowId"),
							win = HteOS.window.WindowManager.get(windowId);
				if (win.active) {
					win.hide();
				} else if (win.hidden === true) {
					win.show();
				} else {
					win.front();
				}
			});

			HteOS.EventManager.on("hte.window.create", function( win) {
				// FIXME 在任务栏新建图标，应该采用事件的方式来处理，暂时先处理
				var task = me.add(win);
				if(!win.animateTarget){
					win.animateTarget = task;
				}
			});

			HteOS.EventManager.on("hte.window.close", function(win) {
				me.remove(win.taskId)
			});

			/*HteOS.EventManager.on(["hte.window.maximize","hte.window.hide",
			"hte.window.show","hte.window.restore"], HteOS.Taskbar.toggle);*/

			HteOS.EventManager.on("hte.window.activate", function(win) {
				$("#hte-task-" + win.taskId).addClass("hte-task-active");
			});
			
			HteOS.EventManager.on("hte.window.deactivate", function(win) {
				$("#hte-task-" + win.taskId).removeClass("hte-task-active");
			});
			
		},
		
		initActions : function(){
			/*var actions = [{
						title : '桌面',
						icon : 'glyphicon glyphicon-home',
						handler : function() {
							var windows = HteOS.window.WindowManager.windows;
							for (var win in windows) {
								HteOS.window.WindowManager.get(win).hide();
							}
							$(".hte-metro-group").css({
										"transform" : "translateX(50px) scale(0.8)",
										"opacity" : 0
									});
							window.setTimeout(function() {
										HteOS.Metro.animate();
									}, 200);
						}
					}, {
						title : '我的HteOS',
						icon : 'glyphicon glyphicon-user',
						handler : function() {
							var app = HteOS.AppManager.getByKey("myhteos");
							HteOS.TaskManager.start(app);
						}
					}, {
						title : '应用管理',
						icon : 'glyphicon glyphicon-list',
						handler : function() {
							HteOS.TaskManager.start({
								id : 'appmanager',
								name : "应用管理",
								path : HteOS.basePath+"tpl/overview.html",
								mode : 'dock'
							});
						}
					}];
			for (var i = 0; i < actions.length; i++) {
				this.addLeftAction(actions[i], false);
			}*/
			var me = this;
			/*$.getJSON(HteOS.basePath + HteOS.API.TRAYS,function(trays){
				for (var i = 0; i < trays.length; i++) {
					var tray = trays[i];
					try{
						tray.handler = new Function(tray.handler);
					}catch(e){
						
					}
					me.addAction(tray,tray.position, false);
				}
				HteOS.EventManager.trigger("hte.taskbar.init");
			});*/
			
			this.actions.forEach(function(action,index){
				try{
					action.handler = new Function(action.handler);
				}catch(e){
					
				}
				me.addAction(action,action.position, false);
			});
			
			/*var actions = [{
						title : '即时通讯',
						icon : 'glyphicon glyphicon-comment',
						handler : function() {
							HteOS.TaskManager.start({
								id : 'messager',
								name : "即时通讯",
								path : HteOS.basePath+"tpl/messager.html",
								mode : 'dock'
							});
						}
					}, {
						title : '个性化设置',
						icon : 'glyphicon glyphicon glyphicon-cog',
						handler : function() {
							var app = HteOS.AppManager.getByKey("settings");
							HteOS.TaskManager.start(app);
						}
					},{
						title : '示例',
						icon : 'glyphicon glyphicon-bookmark',
						handler:function(){
							HteOS.TaskManager.start({
								id : 'example',
								mode : 'window',
								path : HteOS.basePath + 'examples/index.html',
								name : '示例',
								icon : HteOS.basePath + 'images/logo.png'
							});
						}
					}];*/
			/*if(HteOS.User.logon){
				actions.insert(2,{
						title : '锁定屏幕',
						icon : 'glyphicon glyphicon-lock',
						handler : function() {
							HteOS.Locker.lock();
						}
				});
			}
			for (var i = 0; i < actions.length; i++) {
				this.addRightAction(actions[i], false);
			}*/
			
			var time = $("<div class=\"hte-taskbar-action hte-taskbar-action-time\""
			+"data-toggle=\"tooltip\" data-placement=\"top\" data-original-title=\""+new Date().toLocaleDateString()+"\">"
				+ new Date().formatTime()
			+"</div>");
			
			var desktop = $("<div class=\"hte-taskbar-action\""
			+ " style='width:5px;border-left:1px solid #ccc'></div>");
			time.appendTo($(".hte-taskbar-action-right"));
			desktop.appendTo($(".hte-taskbar-action-right"));
			
			window.setInterval(function(){
				time.html(new Date().formatTime());
			},1000*60);
			
			desktop.click(function(){
				var windows = HteOS.window.WindowManager.windows;
				for(var win in windows){
					HteOS.window.WindowManager.get(win).hide();
				}
			});
			this.adjust();
			HteOS.EventManager.trigger("hte.taskbar.init");
		},
		
		
		addLeftAction : function(action,adjust){
			action.position = 'left';
			this.addAction(action,adjust);
		},
		
		addRightAction:function(action,adjust){
			action.position = 'right';
			this.addAction(action,adjust);
		},
		
		addAction : function(config,position, adjust) {
			var action = $("<div class=\"hte-taskbar-action hte-taskbar-action-profile\" "
					+ "data-toggle=\"tooltip\" data-placement=\"top\" data-original-title=\""
					+ config.title
					+ "\">"
					+ "<span class=\"hte-taskbar-action-icon "
					+ config.icon
					+ "\"></span>" + "</div>");
			if (config.app) {
				action.click(function(event) {
					var app = HteOS.AppManager.getByKey(config.app);
					if(!app) return;
					HteOS.TaskManager.start(app);
				});
			}
			if (config.handler) {
				action.click(function(event) {
					event.stopPropagation();
					config.handler();
				});
			}
			if(config.position == 'right'){
				var time = $(".hte-taskbar-action-time");
				if(time.length > 0 ){
					action.insertBefore(time);
				}else{
					action.appendTo($(".hte-taskbar-action-" + position));
				}
			}else{
				action.appendTo($(".hte-taskbar-action-" + position));
			}
			if (adjust !== false) {
				this.adjust();
			}
		},
		
		adjust : function() {
			var el = this.getEl();
			var inner = $(".hte-taskbar-inner");
			inner.css({
						left : $(".hte-taskbar-action-left").outerWidth(),
						right : $(".hte-taskbar-action-right").outerWidth()
					});
		},

		/**
		 * 任务栏切换状态，如果有最大话的窗口则固定在底部，如果没有则不固定在底部
		 */
		toggle: function() {
			var fixed = HteOS.Taskbar.fixed;
			if ($(".hte-window-maximize:visible").length == 0) {
				if (fixed) {
					HteOS.Taskbar.getEl().removeClass("hte-taskbar-fixed");
					HteOS.Taskbar.fixed = false;
					HteOS.Taskbar.layout();
				}
			} else {
				if (!fixed) {
					HteOS.Taskbar.getEl().addClass("hte-taskbar-fixed");
					HteOS.Taskbar.fixed = true;
					HteOS.Taskbar.layout();
				}
			}
		},

		/**
		 * 通过APP实例ID添加任务栏
		 * @param {String} id
		 */
		add: function(win) {
			var task = $("<div class=\"hte-task\" >" + "<img class=\"hte-task-icon\" >" + "<div class=\"hte-task-name\"></div>" + "</div>");
			task.attr("id", "hte-task-" + win.taskId);
			task.data("windowId", win.id);
			// task.css("backgroundColor", app.bgcolor);
			task.find(".hte-task-name").html(win.title);
			task.find("img").attr("src", win.icon);
			// task.attr("data-toggle", "tooltip");
			// task.attr("data-original-title", app.name);
			this.tasks++;
			this.inner.append(task);
			this.layout();
			this.dragdrop();
			return task;
		},

		/**
		 * 通过APP实例ID移除任务栏
		 * @param {String} id
		 */
		remove: function(id) {
			$("#hte-task-" + id).remove();
			this.tasks--;
			this.layout();
		},

		/**
		 * 对任务栏的组件进行调整，如果有溢出则显示溢出导航组件
		 */
		layout: function() {
			if (this.tasks == 0) {
				return;
			}
			var me = HteOS.Taskbar,
				innerWidth, overflow = me.overflow,
				el = me.getEl();
			/*if (!me.fixed) {
				innerWidth = el.outerWidth() - 200;
			} else {
				innerWidth = el.outerWidth() - 50;
			}*/
			innerWidth = el.outerWidth() - $(".hte-taskbar-action-right").outerWidth() - $(".hte-taskbar-action-left").outerWidth();
			if(innerWidth / this.tasks < (this.width + this.margin)){
				$(".hte-task").css('width',innerWidth / this.tasks - this.margin);
			}else{
				$(".hte-task").css('width',this.width);
			}
			/*// 比较是否溢出，如果溢出则将导航按钮显示出来
			var width = $(".hte-task:last").position().left + me.width + 8;
			if (width > innerWidth) {
				if (!overflow) {
					el.addClass("hte-taskbar-overflow");
					me.overflow = true;
				}
			} else {
				if (overflow) {
					el.removeClass("hte-taskbar-overflow");
					me.overflow = false;
				}
			}*/
		},

		/**
		 * 初始化任务栏拖拽
		 */
		dragdrop: function() {
			var me = this;
			$(".hte-task").draggable({
				containment: me.inner,
				revert: false,
				axis: 'x',
				helper : 'clone',
				start: function() {
					//$(this).css("z-index", 1);
					$(this).css("visibility", "hidden");
					//FIXME 兼容IE8样式
				},
				stop: function() {
					$(this).css("visibility", "visible");
				}
			});
			$(".hte-task").droppable({
				accept: ".hte-task",
				over: function(event, ui) {
					var target = $(this),
						source = $(ui.draggable.get(0));
					if (source.position().left < target.position().left) {
						source.insertAfter(target);
					} else {
						source.insertBefore(target);
					}
				},
				drop: function(event, ui) {
					
				}
			});
		},

		/**
		 * 初始化右键菜单
		 */
		contextmenu: function() {
			var windowManager = HteOS.window.WindowManager;
			//创建任务栏右键菜单
			new HteOS.menu.Menu({
				selector: ".hte-task",
				cls: "hte-task-contextmenu",
				items: [{
					id: 'restore',
					name: '还原',
					icon: 'fa fa-window-restore',
					handler: function() {
						var windowId = this.task.data("windowId"),
							win = windowManager.get(windowId);
						if (win) {
							win.restore();
						}
					}
				}, {
					id: 'hide',
					name: '最小化',
					icon: 'fa fa-window-minimize ',
					handler: function() {
						var windowId = this.task.data("windowId"),
							win = windowManager.get(windowId);
						if (win) {
							win.hide();
						}
					}
				}, {
					id: 'maximize',
					name: '最大化',
					icon: 'fa fa-window-maximize',
					handler: function() {
						var windowId = this.task.data("windowId"),
							win = windowManager.get(windowId);
						if (win) {
							win.maximize();
						}
					}
				}, '-', {
					id: 'close',
					name: '关闭',
					icon: 'fa fa-window-close-o',
					handler: function() {
						var windowId = this.task.data("windowId"),
							win = windowManager.get(windowId);
						if (win) {
							win.close();
						}
					}
				}, {
					id: 'closeother',
					name: '关闭其他',
					icon: 'fa fa-window-close',
					handler: function() {
						var windowId = this.task.data("windowId"),
							windows = windowManager.windows;
						for(var win in windows){
							if(win != windowId){
								windowManager.get(win).close();
							}
						}
					}
				}, {
					id: 'closeall',
					name: '关闭所有',
					icon: 'fa fa-window-close',
					handler: function() {
						var windows = windowManager.windows;
						for(var win in windows){
							windowManager.get(win).close();
						}
					}
				}],
				events: {
					show: function(target) {
						var me = this,
							task, el = me.getEl();
						if ($(target).hasClass("hte-task")) {
							task = $(target);
						} else {
							task = $(target).parents(".hte-task");
						}
						me.task = task;
						var windowId = this.task.data("windowId"),
							win = windowManager.get(windowId);
						
						me[win.maximized ? 'disable' : 'enable']('maximize');
						me[win.hidden ? 'disable' : 'enable']('hide');
						me[!win.maximized && !win.hidden ? 'disable' : 'enable']('restore');
						if(win.maximizable !== true){
							me.disable("maximize");
						}
					}
				}
			});
		},

		getEl: function() {
			return $(".hte-taskbar");
		}

	}
}));